import cherrypy
import sqlite3
import os.path
import hashlib

# Import our modules
import Common
import Subforum
import Thread
import Post
import User
import Search
import Structure
import PrivateMessage

# root_dir is used by the config file
root_dir = os.path.dirname(os.path.abspath(__file__))

# connect to the database
def connect(thread_index):
	cherrypy.thread_data.db = sqlite3.connect('forum.db')
cherrypy.engine.subscribe('start_thread', connect)

# the actual forum
class Forum(Common.Template):
	def __init__(self):
		# Register our modules
		self.Subforum = Subforum.Subforum()
		self.Thread = Thread.Thread()
		self.Post = Post.Post()
		self.User = User.User()
		self.Search = Search.Search()
		self.Structure = Structure.Structure()
		self.PrivateMessage = PrivateMessage.PrivateMessage()

	# For the index, just load the root forum display
	def index(self):
		return self.Subforum.default()
	index.exposed = True

	# event: log in or register a user
	def login(self, user = None, passwd = None, reg = None):
		if user and passwd:
			c = cherrypy.thread_data.db.cursor()
			uid = None
			# check if the user pressed register
			if reg:
				c.execute('select ID from User where Username=?', (user,))
				uid = c.fetchone()
				# if the user is not registered
				if uid is None:
					# find a unique id for the new user
					return self.User.registerUserPage(user, passwd)
				else:
					# display an error
					return self.error('Username already exists.')
			# otherwise, the default action is to login
			else:
				# check the database
				c.execute('select ID from User where Username=? AND Password=?', (user, hashlib.md5(passwd).hexdigest(),))
				uid = c.fetchone()
				if uid is None:
					# display an error
					return self.error('Incorrect user/password combination.')
				else:
					uid = uid[0]
				# display an error if the user is banned
				ban = self.banCheck(uid)
				if ban != None:
					return self.error('You are banned. You will be unbanned: %s' % ban, True)
			# create the user's session
			cherrypy.session['ID'] = uid
			cherrypy.session['Username'] = user
			cherrypy.session['Permission'] = c.execute('select Permission from User where ID=?', (uid,)).fetchone()[0]
			# if the user pressed register
			if reg:
				# take them to their user info page
				return self.User.index()
			else:
				# otherwise, redirect them to the page they came from
				#[todo] this seems unstable for some reason
				return self.redirect("javascript:r=document.referrer;if(r.indexOf('logout')!=-1|r.indexOf('login')!=-1){r='/'};location.replace(r)")
		else:
			# display an error
			return self.error('One or more login fields are blank.')
			#raise cherrypy.HTTPError(401)
	login.exposed = True

	# event: log out a user
	def logout(self):
		# destroy the user's session
		cherrypy.session['ID'] = None
		cherrypy.session['Username'] = None
		cherrypy.session['Permission'] = 3
		return self.index()
	logout.exposed = True

	# event: user pressed search
	# this function must be here, otherwise it won't capture the GET requests
	def search(self, q = None):
		return self.Search.default(q)
	search.exposed = True

# Load the config file
conf = os.path.join(os.path.dirname(__file__), 'forum.conf')

# This is how they start the server in the tutorials
if __name__ == '__main__':
    cherrypy.quickstart(Forum(), config=conf)
else:
    cherrypy.tree.mount(Forum(), config=conf)
